$(function () {

    // 缓存
    var currentRoleId = null,
        roleCache = {}, //角色列表
        employeeCache = null,
        group = {}, //权限列表
        employeeDiv = $("#employeeDiv");

    var initRoles = function () {
        chinese.sEmptyTable = "尚未添加角色";
        var table = $('#roleTable').DataTable({
            "ajax": "permission/listRoles",
            "sort": false,
            "aoColumnDefs": [
                {
                    "targets": 0, // 折叠按钮
                    "className": 'details-control',
                    "mRender": function (data, type, row) {
                        return '<span class="glyphicons glyphicons-circle_plus text-system cursor-pointer fs14"></span>';
                    }
                }, {
                    "targets": 1, // 角色名称
                    "mRender": function (data, type, row) {
                        return row.name;
                    }
                }, {
                    "targets": 2, // 说明
                    "mRender": function (data, type, row) {
                        return row.description ? row.description : '无';
                    }
                }, {
                    "targets": 3, // 员工数
                    "mRender": function (data, type, row) {
                        return row.members.length;
                    }
                }, {
                    "targets": 4, // 操作
                    "mRender": function (data, type, row) {
                        return sys.render("#roleBtns", row);
                    }
                }],
            "order": [1, 'asc'],
            "oLanguage": chinese,
            "sDom": 't',
            "initComplete": function (settings, json) {
                //$(".repay-table-title").html('<i class="fa fa-table mr5"></i><span class="fs14">还款计划详情</span><code class="investCount">共' + json.recordsTotal + '期</code>');
                $.map(json.data, function (role) {
                    roleCache[role.id] = role;
                });
            },
            "rowCallback": function (row, data, index) {
                $(row).data("id", data.id).addClass("cursor-pointer text-muted");
            }
        });
        /**
         * 详情展开/关闭
         */
        $('#roleTable tbody').on('click', 'td.details-control', function (e) {
            e.preventDefault();
            e.stopPropagation();

            var tr = $(this).closest('tr');
            var row = table.row(tr);

            if (row.child.isShown()) {
                // 关闭详情
                $(this).html('<span class="glyphicons glyphicons-circle_plus text-system cursor-pointer fs14"></span>');
                row.child.hide();
                tr.removeClass('shown');
            }
            else {
                // 展开详情
                $(this).html('<span class="glyphicons glyphicons-circle_minus text-info cursor-pointer fs14"></span>');
                var role = roleCache[row.data().id],
                    detail = '<p class="text-center mt20 mb20">尚未添加员工</p>';

                role.status = function () {
                    return this.enabled ? '正常' : '冻结';
                };
                role.rid = function () {
                    return role.id;
                };
                if (role.members.length > 0) {
                    detail = sys.render("#roleEmployeeTemplate", role);
                }
                row.child(detail).show();
                tr.addClass('shown');
            }
        });
    };

    /**
     * 保存角色
     * 
     * @param {type} id
     * @returns {undefined}
     */
    var saveRole = function (role) {
        $.post("permission/saveRole", role, function (res) {
            alert(res.message);
            if (res.success) {
                location.reload();
            }
        }).fail(function () {
            alert("服务器错误");
        });
    };

    /**
     * 加载权限列表
     */
    var loadPermissions = function () {
        var leftCol = $(".leftCol"),
            rightCol = $(".rightCol");

        $.get("permission/listPermissions", function (data) {
            if (data && data.length > 0) {
                var groupSize = 0;
                for (var i = 0; i < data.length; i++) {
                    var permission = data[i];
                    if (permission.group in group) {
                        group[permission.group].push(permission);
                    } else {
                        group[permission.group] = [permission];
                        groupSize++;
                    }
                }
                var map = {};
                $(".p-load-info").hide();
                var mid = groupSize / 2, count = 0;
                for (var key in group) {
                    var ps = group[key], groupLabel = $('<label class="control-label mb15"></label>').html(key);
                    map.result = ps;
                    var rendered = sys.render("#permissionTemplate", map);
                    if (count < mid) {
                        leftCol.append(groupLabel).append($('<div class="form-group mn mb10 pl20"></div>').html(rendered));
                    } else {
                        rightCol.append(groupLabel).append($('<div class="form-group mn mb10 pl20"></div>').html(rendered));
                    }
                    count++;
                }
            } else {
                $("#permissions .load-info").text("尚未添加权限");
            }
            //ajaxSuccess();
        }).fail(function () {
            alert("加载权限列表失败：服务器错误");
        });
    };

    var openModal = function (target) {
        $.magnificPopup.open({
            removalDelay: 500, //delay removal by X to allow out-animation,
            alignTop: true,
            closeBtnInside: false,
            items: {
                src: target
            },
            callbacks: {
                beforeOpen: function (e) {
                    this.st.mainClass = 'mfp-slideDown';
                }
            },
            midClick: true // allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source.
        });
    };

    /**
     * 按钮事件
     */
    var initEvents = function () {
        /**
         * 查看角色权限
         */
        $('#roleTable tbody').on('click', 'tr', function (e) {
            $("#roleTable tbody tr").removeClass("selected");
            $(this).addClass("selected");
            var id = $(this).data("id"), role = roleCache[id];
            currentRoleId = id;
            $(".permission_checkbox").prop("checked", false);
            // 读取权限列表
            for (var i = 0; i < role.permissions.length; i++) {
                var permission = role.permissions[i];
                $(".permission_checkbox[value=" + permission.name + "]").prop("checked", true);
            }
        });

        var getPermissions = function () {
            var permissions = [];
            $.map($(".permission_checkbox:checked"), function (box) {
                permissions.push($(box).val());
            });
            return permissions.join(",");
        };

        var getMembers = function () {
            var members = [];
            $.map($(".member_checkbox:checked"), function (box) {
                members.push($(box).val());
            });
            return members.join(",");
        };

        /**
         * 保存角色权限
         */
        $("#saveRolePermission").on("click", function () {
            if (currentRoleId === null) {
                return;
            }

            var role = roleCache[currentRoleId];
            role.permissions = getPermissions();
            saveRole(role);
        });

        /**
         * 添加角色
         */
        $("#add_role").on("click", function () {
            currentRoleId = null;
            openModal("#addRolePanel");
        });

        /**
         * 保存角色
         */
        var name = $("#roleName"), description = $("#description");
        $("#saveRoleBtn").on("click", function () {
            if (name.val() === '') {
                alert("请输入角色名称");
                name.focus();
                return;
            }
            var role = {
                id: currentRoleId,
                name: name.val(),
                description: description.val(),
                permissions: currentRoleId ? getPermissions() : '',
                members: ''
            };
            saveRole(role);
        });

        /**
         * 编辑角色
         */
        $('#roleTable tbody').on('click', '.edit-role-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            var id = $(this).data("id"), role = roleCache[id];
            currentRoleId = id;
            name.val(role.name);
            description.val(role.description);
            openModal("#addRolePanel");
        });

        /**
         * 删除角色
         */
        $('#roleTable tbody').on('click', '.delete-role-link', function (e) {
            e.stopPropagation();
            e.preventDefault();
            var url = "permission/deleteRole/" + $(this).data("id");
            if (confirm("确定删除角色")) {
                $.get(url, function (res) {
                    if (res) {
                        alert("角色已删除");
                        location.reload();
                    } else {
                        alert("角色删除失败");
                    }
                }).fail(function () {
                    alert("服务器错误");
                });
            }
        });

        /**
         * 添加成员
         */
        $('#roleTable tbody').on('click', '.add-member-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            var id = $(this).data("id"), role = roleCache[id];
            if (employeeCache === null) {
                alert("员工列表为空");
                return;
            }
            $(".member_checkbox").prop("checked", false);
            $(".member_checkbox_div").removeClass("hidden");


            if (role.members.length === employeeCache.length) {
                sys.alert("暂无可添加员工");
                return;
            }

            openModal("#addEmployeePanel");

            for (var i = 0; i < role.members.length; i++) {
                var eid = role.members[i].id;
                $("#m-" + eid).addClass("hidden");
            }
            currentRoleId = id;
        });

        /**
         * 保存角色成员
         */
        $('#saveMemberBtn').on('click', function (e) {
            var btn = $(this), members = getMembers();
            if (currentRoleId === null) {
                alert("角色未选择");
                return;
            }
            if (members === '') {
                alert("请选择要添加的员工");
                return;
            }
            sys.btnSpin(btn);
            $.post("permission/saveRoleForEmployees", {
                roleId: currentRoleId,
                addIdString: members,
                cancelIdString: ''
            }, function (res) {
                alert(res.message);
                if (res.success) {
                    location.reload();
                }
                sys.btnStop(btn);
            }).fail(function () {
                alert("网络通信错误");
                sys.btnStop(btn);
            });
        });

        /**
         * 删除成员
         */
        $('#roleTable tbody').on('click', '.delete-member-link', function (e) {
            e.preventDefault();
            e.stopPropagation();

            var id = $(this).data("id"), roleId = $(this).data("rid");
            if (id === '' || roleId === '') {
                alert("角色或员工未找到");
                return;
            }
            if (confirm("确定要删除成员？")) {
                $.post("permission/saveRoleForEmployees", {
                    roleId: roleId,
                    addIdString: "",
                    cancelIdString: id
                }, function (res) {
                    alert(res.message);
                    if (res.success) {
                        location.reload();
                    }
                }).fail(function () {
                    alert("网络通信错误");
                });
            }
        });
    };

    /**
     * 读取员工列表
     */
    var loadEmployees = function () {
        $.get("employee/getData", function (res) {
            if (res) {
                employeeCache = res.data;
                var rendered = sys.render("#memberTemplate", {result: res.data});
                employeeDiv.html(rendered);
            }
        });
    };

    initRoles();
    loadPermissions();
    initEvents();
    loadEmployees();
});